package me.dengfengdecao.android.photogallery;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;

/**
 * 在应用中显现图片
 */
public class PhotoPageFragment extends VisibleFragment {

    private String mPicUrl;
    private WebView mWebView;
    private TextView mTitleTextView;
    private ProgressBar mProgressBar;

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
        // 从托管的activity中取得附加数据
        mPicUrl = getActivity().getIntent().getDataString();
    }

    @SuppressLint("SetJavaScriptEnabled")
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // 转发从intent数据中获取的URL
        View v = inflater.inflate(R.layout.fragment_photo_page, container, false);

        mWebView = (WebView) v.findViewById(R.id.webView);              // WebView
        mTitleTextView = (TextView) v.findViewById(R.id.titleTextView); // 标题
        mProgressBar = (ProgressBar) v.findViewById(R.id.progressBar);  // 进度条
        mProgressBar.setMax(100);   // 范围在0~100

        // 设置JavaScript为启用
        mWebView.getSettings().setJavaScriptEnabled(true);
        // 返回false，意为WebView去加载URL，本人不做任何处理
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
            }
        });

        // 关联标题与进度条
        mWebView.setWebChromeClient(new WebChromeClient() {
            // 标题的更新回调方法
            @Override
            public void onReceivedTitle(WebView view, String title) {
               mTitleTextView.setText(title);
            }

            // 进度条的更新回调方法
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    mProgressBar.setVisibility(View.INVISIBLE);
                } else {
                    mProgressBar.setVisibility(View.VISIBLE);
                    mProgressBar.setProgress(newProgress);
                }
            }
        });

        // 加载URL网页
        mWebView.loadUrl(mPicUrl);

        return v;
    }
}
